package com.example.mvvm.demo

import android.os.Bundle
import androidx.activity.viewModels
import androidx.fragment.app.commit
import androidx.lifecycle.Observer
import com.example.base.adapter.VbAdapter
import com.example.base.adapter.holder.VBHolder
import com.example.base.adapter.into
import com.example.base.base.BaseBindingActivity
import com.example.base.base.BaseViewModel
import com.example.base.base.VmLiveData
import com.example.base.base.vmObserver
import com.example.base.eventlivedata.EventLiveData
import com.example.mvvm.databinding.ActivityBindingBinding
import com.example.mvvm.databinding.ItemTestBinding
import kotlinx.coroutines.delay

class BindingActivity : BaseBindingActivity<ActivityBindingBinding>() {

    private val viewModel by viewModels<BindingActivityViewModel>()
    private val adapter = BindingActivityAdapter()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        supportFragmentManager.commit { add(binding.fragment1.id, BindingBlankFragment()) }
        binding.btnDialog.setOnClickListener {
            BindingBlankDialog().show(supportFragmentManager, "")
        }
        adapter.into(binding.recy)
//        adapter.addItem(0, viewModel.name)
        viewModel.name.vmObserver(this) {
            onBefore
        }
    }

}

class BindingActivityViewModel: BaseViewModel() {

    private val repository by lazy { BindingActivityRepository() }

    val name = VmLiveData<String>()

    fun refreshNameTask() {
        name.vmTask {
            return@vmTask repository.updateName()
        }
    }
//    fun refreshNameTask(): SingleTask<Unit> {
//        return singleTask { repository.refreshName(name) }
//    }
}

class BindingActivityRepository {

    suspend fun refreshName(name: EventLiveData<String>) {
        for (i in 1 .. 10) {
            delay(1000)
            name.submitValue("大猩猩${i}号")
        }
    }

    suspend fun updateName(): String {
        return "大猩猩"
    }
}

// 用ViewBinding的
class BindingActivityAdapter : VbAdapter<EventLiveData<String>, ItemTestBinding>() {

    override fun fillData(rvHolder: VBHolder<ItemTestBinding>, position: Int, model: EventLiveData<String>?) {
        val item = model ?: return
        item.observeSticky(this, Observer {
            rvHolder.binding.tvName.text = it
        })
    }
}
